﻿using System;
using System.Collections.Generic;
using System.ComponentModel;

namespace SrBBSPro.BaseClasses
{
    /// <summary>
    /// Base class for entities
    /// </summary>
    public abstract class BaseEntity<TId>
    {
        private readonly List<BusinessRule> _brokenRules = new List<BusinessRule>();

        public TId Id { get; set; }

        public override bool Equals(object entity)
        {
            return entity != null && entity is BaseEntity<TId> && this == (BaseEntity<TId>)entity;
        }
        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }

        public static bool operator ==(BaseEntity<TId> entity1,
           BaseEntity<TId> entity2)
        {
            if ((object)entity1 == null && (object)entity2 == null)
            {
                return true;
            }

            if ((object)entity1 == null || (object)entity2 == null)
            {
                return false;
            }

            if (entity1.Id.ToString() == entity2.Id.ToString())
            {
                return true;
            }

            return false;
        }

        public static bool operator !=(BaseEntity<TId> entity1,
            BaseEntity<TId> entity2)
        {
            return (!(entity1 == entity2));
        }

        public void SetProp<T>(T t)
        {
            foreach (var prop in t.GetType().GetProperties())
            {
                var db = this.GetType().GetProperty(prop.Name);
                if (db != null)
                {
                    db.SetValue(this, prop.GetValue(t));
                }
            }
        }      

        public int MinusDate(DateTime end, DateTime start)
          => (int)end.Subtract(start).TotalDays +1;

        public Dictionary<string, string> GetValAndDes()
        {
            var dic = new Dictionary<string, string>();
            foreach (var prop in GetType().GetProperties())
            {
                if (prop.Name.Equals("Id") || prop.Name.Equals("UserId") || prop.Name.Equals("User"))
                    continue;
                object[] obs = prop.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (obs.Length > 0)
                {
                    var des = obs[0] as DescriptionAttribute;
                    dic.Add(prop.Name, des.Description);
                }
                else
                {
                    dic.Add(prop.Name, prop.Name);
                }
            }
            return dic;
        }
    }
}